package com.store.app.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.store.app.ExitApplication;
import com.store.app.LocationApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.IDUtil;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.ToastUtils;
import com.store.app.zxing.Capture_ZxingActivity;

import org.json.JSONObject;

/**
 * 亲情卡收款
 */

public class FamilyCardPayCaptureActivity extends Capture_ZxingActivity implements IOnHttpListener {

    private TextView title_tv;
    private String money="0.0";
    private TextView tv_cap,tv_cap_money;
    private NetRequest netRequest;
    private String s_cardno="";
    private  String member_id;
    private String out_trade_no;
    private String price_original;
    private String discount_price;
    private String dikouData;
    private String rebateData;
    private String rewardData;
    private String transaction_no;
    @Override
    public void onAfinalFail() {
        handler.sendEmptyMessageDelayed(1, 5000);
        dismissProgressDialog();
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        dismissProgressDialog();
        if(requestId == 1) {
            Log.i("zyl","1 "+result);
            //收款成功，调接口通知服务器，服务器自己玩，看看需不需要返现。
            try {
                JSONObject jsonObject = new JSONObject(result);
                 member_id = jsonObject.getString("member_id");
                String usable_balance = jsonObject.getString("usable_balance");
                String num=MoneyUtil.moneySub(usable_balance,money);
                if(Double.parseDouble(num)<0){
                    Toast.makeText(FamilyCardPayCaptureActivity.this,"消费者余额不足",Toast.LENGTH_SHORT).show();
                    handler.sendEmptyMessageDelayed(1, 5000);
                    return;
                }
                out_trade_no = IDUtil.getOutTradeNo();
                Log.v("zyl","亲情卡支付时候的out_trade_no："+out_trade_no);
                netRequest.requestFamilyPay(2, member_id, money,s_cardno,out_trade_no);
            } catch (Exception e) {
                Toast.makeText(FamilyCardPayCaptureActivity.this,"亲情卡支付失败",Toast.LENGTH_SHORT).show();
                handler.sendEmptyMessageDelayed(1, 5000);
            }
        }else if(requestId == 2){
            Log.i("zyl","2 "+result);
            //收款成功，调接口通知服务器，服务器自己玩，看看需不需要返现。
            try {
                JSONObject jsonObject = new JSONObject(result);
                 transaction_no = jsonObject.getString("transaction_no");

                //调用促销规则
                netRequest.requestStoreCashierPromotion(3,out_trade_no,
                        member_id,
                        MainActivity.member_id,
                        "亲情卡",SettingData.PAYMENT_WAY_05,
                        price_original,
                        discount_price,
                        dikouData,
                        rebateData
                        ,rewardData
                        ,money
                        ,transaction_no,"",s_cardno);
            }catch (Exception e){}
        }else if(requestId == 3){
            Log.v("zyl","调用促销规则成功");
            Intent intent = new Intent();
            intent.putExtra("resultMoney",money);
            intent.putExtra("card_no",s_cardno);
            intent.putExtra("buyer_id",member_id);
            intent.putExtra("out_trade_no",out_trade_no);
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                setReCapture();
            }
        }
    };

    @Override
    public void onExecuteFail(int requestId, String msg) {
        dismissProgressDialog();
        ToastUtils.showTextToast(FamilyCardPayCaptureActivity.this, msg);
        handler.sendEmptyMessageDelayed(1, 5000);
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        netRequest = new NetRequest(this);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_wechat_capture);
        getWindow()
                .addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        money = getIntent().getStringExtra("money");
        price_original = getIntent().getStringExtra("price_original");
        discount_price = getIntent().getStringExtra("discount_price");
        dikouData = getIntent().getStringExtra("dikouData");
        rebateData = getIntent().getStringExtra("rebateData");
        rewardData = getIntent().getStringExtra("rewardData");

        Log.v("zyl","FamilyCardPayCaptureActivity:"+money);
        setInintView();
        findViewById();
    }


    private void findViewById() {
        findViewById(R.id.retreat).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText("亲情卡收款");
        tv_cap = (TextView) findViewById(R.id.cap_tv);
        tv_cap_money= (TextView) findViewById(R.id.cap_tv_money);
        int width = LocationApplication.app.getDM().widthPixels;
        int high = LocationApplication.app.getDM().heightPixels;
        width = width / 8 * 3;
        high = high / 2 + width;
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.topMargin = high + MainActivity.dip2px(20);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        tv_cap.setLayoutParams(layoutParams);
        tv_cap.setText("扫描亲情卡上的二维码，即可亲情卡支付");
        tv_cap_money.setText(money);
    }

    /**
     * 处理扫描结果
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();

        if (!TextUtils.isEmpty(resultString)) {
            if (resultString.length() > 3) {
                String identifying = resultString.substring(0, 3);
                if (identifying.equals("MTH")) {

                    Log.v("zyl", "亲情卡支付");
                    if (!TextUtils.isEmpty(MainActivity.member_id)) {
                        showProgressDialog("亲情卡收款", "收款中……");
                        netRequest.requestCheckFamilyCard(1, resultString);
                       // netRequest.requestCardPay(1, MainActivity.member_id, resultString, money + "");
                        s_cardno=resultString;

                    }
                } else {
                    handler.sendEmptyMessageDelayed(1,5000);
                    Toast.makeText(FamilyCardPayCaptureActivity.this, "此二维码非亲情卡！", Toast.LENGTH_SHORT).show();
                }
            }
        } else {
            Toast.makeText(FamilyCardPayCaptureActivity.this, "无法识别此二维码!", Toast.LENGTH_SHORT).show();
            handler.sendEmptyMessageDelayed(1,5000);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
